'use strict'
module.exports = () => {
  return async function (ctx, next) {
    const { config } = ctx.app
    const { apiPath } = config
    // 白名单
    const whileArr = [
      '/admin/login',
      '/common/get_oss_url',
      '/common/send_verify',
      '/common/get_oss_post_object_params',
      '/common/send_notify',
      '/common/upload',
      '/common/uploadCar',
      '/common/create_default_menus_table',
      '/common/create_default_question_table',
      '/refresh/refresh_wx_token',
      '/wechat/receive_notice',
      '/wechat/GetWxUserList',
    ]
    // 先屏蔽小程序
    const isMina = ctx.url.startsWith(`${apiPath}/mina`)
    if (isMina) {
      await next()
      return
    }
    // 屏蔽socket
    const isIo = ctx.url.startsWith('/io')
    if (isIo) {
      await next()
      return
    }
    for (const item in whileArr) {
      if (ctx.url.startsWith(`${apiPath}${whileArr[item]}`)) {
        await next()
        return
      }
    }
    if (ctx.get('Authorization')) {
      // console.log(ctx.get('Authorization'))
      const token = ctx.get('Authorization')
      let info
      try {
        info = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret)
      } catch (error) {
        if (error.name == 'TokenExpiredError') {
          /** 401 http错误 未经授权,访问由于凭证无效而被拒绝 */
          ctx.body = {
            msg: 'token过期',
            code: 401,
          }
          return
        }
        ctx.body = {
          code: 401,
          msg: 'token失效',
        }
        return
      }
      ctx.user = info
      await next()
    } else {
      ctx.status = 401
      ctx.body = {
        msg: 'no token detected in http header Authorization',
      }
      return
    }
  }
}
